package ge.telasi.tasks.search;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.Query;

/**
 * A very simple condition interface.
 *
 * @author dimitri
 */
public class Condition implements Serializable {
    private static final long serialVersionUID = 2846279301508930468L;

    private static Properties properties;
    static {
        try {
            properties = new Properties();
            properties.load(Condition.class.getResourceAsStream("search.properties"));
        } catch (Exception ex) {}
    }

    private String condition;
    private Map<String, Object> substitutions = new HashMap<String, Object>();

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public Map<String, Object> getSubstitutions() {
        return substitutions;
    }

    public static String getFullCondition(List<Condition> conditions) {
        StringBuilder b = new StringBuilder();
        boolean first = true;
        for (Condition condition : conditions) {
            if (!first) {
                b.append(" AND ");
            }
            b.append(" ( ");
            b.append(condition.getCondition());
            b.append(" ) ");
            first = false;
        }
        String condition = b.toString();
        for (Object key : properties.keySet()) {
            String val = properties.getProperty(key.toString());
            condition = condition.replace("${" + key + "}", val);
        }
        return condition;
    }

    public static void applyParameters(Query query, List<Condition> conditions) {
        Map<String, Object> params = new HashMap<String, Object>();
        for (Condition condition : conditions) {
            params.putAll(condition.getSubstitutions());
        }
        for (String key : params.keySet()) {
            query.setParameter(key, params.get(key));
        }
    }

}
